Custom Exceptions তৈরি করা
কটলিনে Custom Exceptions তৈরি করা একটি সাধারণ প্রক্রিয়া যা আপনাকে আপনার প্রোগ্রামের জন্য নির্দিষ্ট ত্রুটির অবস্থা সংজ্ঞায়িত করতে দেয়। এটি আপনার কোডের রিডেবিলিটি এবং ব্যবহারকারীদের কাছে আরও স্পষ্ট ত্রুটি বার্তা প্রদান করতে সাহায্য করে। নিচে কটলিনে Custom Exceptions তৈরি করার প্রক্রিয়া এবং উদাহরণ দেওয়া হলো:
১. Custom Exception তৈরি করা
Custom Exception তৈরি করতে, আপনাকে একটি ক্লাস তৈরি করতে হবে যা Exception ক্লাস বা তার সাবক্লাস (যেমন RuntimeException) থেকে ইনহেরিট করবে।
i) Custom Exception Class তৈরি করা
উদাহরণ:
class InsufficientFundsException(message: String) : Exception(message)
ব্যাখ্যা:
- এখানে
InsufficientFundsExceptionনামে একটি Custom Exception ক্লাস তৈরি করা হয়েছে, যাExceptionক্লাস থেকে ইনহেরিট করছে। - এটি একটি কনস্ট্রাক্টর গ্রহণ করে, যা ত্রুটি বার্তা ধারণ করবে।
২. Custom Exception ব্যবহার করা
Custom Exception ব্যবহার করতে, আপনাকে একটি ফাংশনে ত্রুটির অবস্থায় throw কিওয়ার্ড ব্যবহার করে Custom Exceptionটি ছুঁড়তে হবে।
ii) Custom Exception ছুঁড়া
উদাহরণ:
fun withdraw(amount: Double, balance: Double) {
if (amount > balance) {
throw InsufficientFundsException("Insufficient funds: tried to withdraw $amount but balance is only $balance.")
}
println("Withdrawal successful: $amount")
}
fun main() {
val balance = 100.0
try {
withdraw(150.0, balance)
} catch (e: InsufficientFundsException) {
println("Caught an exception: ${e.message}") // আউটপুট: Caught an exception: Insufficient funds: tried to withdraw 150.0 but balance is only 100.0.
}
}
ব্যাখ্যা:
- এখানে
withdrawফাংশনে চেক করা হয়েছে যেamountব্যালেন্সের চেয়ে বেশি কিনা। যদি তাই হয়, তবেInsufficientFundsExceptionছোঁড়া হয়। mainফাংশনেwithdrawফাংশন কল করা হয়েছে এবংtry-catchব্লক ব্যবহার করে Custom Exceptionটি ধরা হয়েছে।
৩. Custom Exception এর কার্যকারিতা
Custom Exceptions এর মাধ্যমে আপনি স্পষ্ট এবং কাস্টমাইজড ত্রুটি বার্তা প্রদান করতে পারেন যা কোডের রিডেবিলিটি এবং ডিবাগিং প্রক্রিয়া সহজ করে।
iv) Custom Exception এর বিভিন্ন ধরনের বার্তা
Custom Exception এ ভিন্ন ভিন্ন কনস্ট্রাক্টর তৈরি করে ভিন্ন ভিন্ন ধরনের বার্তা প্রদান করতে পারেন।
উদাহরণ:
class InsufficientFundsException : Exception {
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
}
fun main() {
try {
throw InsufficientFundsException("Insufficient funds.")
} catch (e: InsufficientFundsException) {
println("Caught an exception: ${e.message}")
}
}
ব্যাখ্যা:
- এখানে
InsufficientFundsExceptionক্লাসে দুটি কনস্ট্রাক্টর তৈরি করা হয়েছে, একটি সাধারণ ত্রুটি বার্তা এবং অন্যটি একটি ত্রুটির কারণের সাথে।
উপসংহার
কটলিনে Custom Exceptions তৈরি করা সহজ এবং এটি আপনাকে আপনার প্রোগ্রামে নির্দিষ্ট ত্রুটির অবস্থা পরিচালনা করতে সক্ষম করে। Custom Exception ব্যবহার করে আপনি আপনার কোডের রিডেবিলিটি বাড়াতে পারেন এবং ব্যবহারকারীদের কাছে আরও স্পষ্ট ত্রুটি বার্তা প্রদান করতে পারেন।
Read more